"""JIRA support for the UMB message sender."""

import os
import re
from urllib import parse

from cki_lib import misc
from cki_lib import session

SESSION = session.get_session(__name__, raise_for_status=True)


def qa_contacts(issue_urls: list[str]) -> list[str]:
    """Return the email addresses of QA contacts for the given list of JIRA issues."""
    if not (issuelist := [i for j in issue_urls for i in re.findall(r"RHEL-\d+", j)]):
        return []

    jira_server = os.environ.get('JIRA_SERVER')
    jira_token_auth = os.environ.get('JIRA_TOKEN_AUTH')
    if not jira_server or not jira_token_auth:
        return []

    qa_contact_field = 'customfield_12315948'

    result = SESSION.get(
        parse.urljoin(jira_server, 'rest/api/2/search'),
        headers={'Authorization': 'Bearer ' + jira_token_auth},
        params={
            'jql': f'key in ({",".join(issuelist)})',
            'fields': qa_contact_field,
            'maxResults': 1000,
        },
    ).json()

    return list({
        e for i in result['issues']
        if (e := misc.get_nested_key(i, f'fields/{qa_contact_field}/emailAddress'))
    })
